<template>
  <div id="hezi">
    <div class="right">
      <div class="buttons">
        <el-button type="primary" @click="handleAdd">新增用户</el-button>
        所在部门
        <el-select
          v-model="selectedOption"
          placeholder="请选择"
          @change="searchByOption"
        >
          <el-option
            v-for="option in uniqueSectionOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          ></el-option>
        </el-select>
        系统权限
        <el-select
          v-model="selectedOptionA"
          placeholder="请选择"
          @change="searchByOptionA"
        >
          <el-option label="权限A" value="权限A"></el-option>
          <el-option label="权限B" value="权限B"></el-option>
          <el-option label="权限C" value="权限C"></el-option>
        </el-select>
        <el-input
          v-model="formInline.search"
          placeholder="请输入用户姓名"
          @blur="search"
          @keyup.native.enter="resetSearch"
        ></el-input>
      </div>
      <el-table :data="tableData" border>
        <el-table-column prop="id" label="用户编号"></el-table-column>
        <el-table-column prop="name" label="用户姓名"></el-table-column>
        <el-table-column prop="bumen" label="部门"></el-table-column>
        <el-table-column prop="quanxian" label="权限"></el-table-column>
        <el-table-column prop="time" label="创建时间"></el-table-column>
        <el-table-column prop="ren" label="创建人"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button type="text" @click="handleLook(scope.row)"
              >查看</el-button
            >
            <el-popconfirm
              @confirm="deleteDepartment(scope.row)"
              title="确定删除该数据吗？"
              style="margin-left: 8px"
            >
              <el-button type="text" slot="reference">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex-container">
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="pageSizeOptions"
            :page-size="100"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 新增部门模态框 -->
    <el-dialog
      title="新增用户"
      :visible="isAddDialogVisible"
      @close="handleAddDialogClose"
      width="600px"
    >
      <div class="dialog-content">
        <el-form :model="newDepartment" label-position="top">
          <el-form-item label="用户编码">
            <el-input
              v-model="newDepartment.id"
              class="custom-input"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户姓名">
            <el-input
              v-model="newDepartment.name"
              class="custom-input"
            ></el-input>
          </el-form-item>
          <el-form-item label="部门">
            <el-select
              v-model="newDepartment.bumen"
              class="custom-input"
              style="width: 400px"
            >
              <el-option
                v-for="option in uniqueSectionOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="权限">
            <el-select
              v-model="newDepartment.quanxian"
              class="custom-input"
              style="width: 400px"
            >
              <el-option label="权限A" value="权限A"></el-option>
              <el-option label="权限B" value="权限B"></el-option>
              <el-option label="权限C" value="权限C"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="newDepartment.time"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="创建人">
            <el-input
              v-model="newDepartment.ren"
              class="custom-input"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleAddDialogClose">取消</el-button>
        <el-button type="primary" @click="handleAddDepartment">确认</el-button>
      </div>
    </el-dialog>

    <!-- 编辑部门模态框 -->
    <el-dialog
      title="编辑用户"
      :visible="isEditDialogVisible"
      @close="handleEditDialogClose"
      width="600px"
    >
      <div class="dialog-content">
        <el-form :model="editDepartment" label-position="top">
          <el-form-item label="用户编码">
            <el-input
              v-model="editDepartment.id"
              class="custom-input"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户姓名">
            <el-input
              v-model="editDepartment.name"
              class="custom-input"
            ></el-input>
          </el-form-item>
          <el-form-item label="部门">
            <el-select
              v-model="editDepartment.bumen"
              class="custom-input"
              style="width: 400px"
            >
              <el-option
                v-for="option in uniqueSectionOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="权限">
            <el-select
              v-model="editDepartment.quanxian"
              class="custom-input"
              style="width: 400px"
            >
              <el-option label="权限A" value="权限A"></el-option>
              <el-option label="权限B" value="权限B"></el-option>
              <el-option label="权限C" value="权限C"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="editDepartment.time"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="创建人">
            <el-input
              v-model="editDepartment.ren"
              class="custom-input"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleEditDialogClose">取消</el-button>
        <el-button type="primary" @click="handleSaveDepartment">确认</el-button>
      </div>
    </el-dialog>

    <!-- 查看部门模态框 -->
    <el-dialog
      title="查看用户"
      :visible="isViewDialogVisible"
      @close="handleViewDialogClose"
      width="600px"
    >
      <div class="dialog-content">
        <el-form :model="viewDepartment" label-position="top">
          <el-form-item label="用户编码">
            <el-input
              v-model="viewDepartment.id"
              class="custom-input"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="用户姓名">
            <el-input
              v-model="viewDepartment.name"
              class="custom-input"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="部门">
            <el-input
              v-model="viewDepartment.bumen"
              class="custom-input"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="权限">
            <el-input
              v-model="viewDepartment.quanxian"
              class="custom-input"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-input
              v-model="viewDepartment.time"
              class="custom-input"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="创建人">
            <el-input
              v-model="viewDepartment.ren"
              class="custom-input"
              disabled
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleViewDialogClose">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="确认删除"
      :visible="isConfirmDeleteVisible"
      @close="resetConfirmDelete"
      width="30%"
      center
    >
      <span class="wen"
        >确定要删除部门 "{{
          confirmDeleteDepartment && confirmDeleteDepartment.name
        }}" 吗？</span
      >
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDepartment">确定</el-button>
        <el-button @click="resetConfirmDelete">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      pageSizeOptions: [5, 4, 3],
      selectedOption: "",
      selectedOptionA: "",
      treeInput: "",
      formInline: {
        search: "",
      },
      newDepartment: {
        id: "",
        name: "",
        bumen: "",
        quanxian: "",
        time: "",
        ren: "",
        status: "",
      },
      editDepartment: {
        id: "",
        name: "",
        bumen: "",
        quanxian: "",
        time: "",
        ren: "",
      },
      viewDepartment: {
        id: "",
        name: "",
        bumen: "",
        quanxian: "",
        time: "",
        ren: "",
      },
      data: [],
      tableData: [],
      total: 0,
      page: 1,
      count: 5,
      isAddDialogVisible: false,
      isEditDialogVisible: false,
      isViewDialogVisible: false,
      isConfirmDeleteVisible: false,
      confirmDeleteDepartment: null,
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },
  computed: {
    uniqueSectionOptions() {
      const uniqueNames = [
        ...new Set(this.data.map((section) => section.name)),
      ];
      return uniqueNames.map((name) => ({ label: name, value: name }));
    },
  },
  methods: {
    handleSizeChange(v) {
      this.count = v;
      this.page = 1;
      this.getData();
    },
    searchByOption() {
      if (this.selectedOption) {
        this.search();
      } else {
        this.resetSearch();
      }
    },
    searchByOptionA() {
      if (this.selectedOptionA) {
        this.search();
      } else {
        this.resetSearch();
      }
    },
    resetSearch() {
      this.formInline.search = "";
      this.selectedOption = "";
      this.selectedOptionA = "";
      this.search();
    },
    handleCurrentChange(v) {
      console.log(v);
      this.page = v;
      this.getData();
    },
    getSectionData() {
      this.$axios
        .get("/section") // 请求/section获取部门数据
        .then(({ data }) => {
          this.data = data; // 将获取到的部门数据赋给data属性
          this.tableData = [];
          this.total = 0;

          // 对部门名称去重
          const uniqueNames = [...new Set(data.map((section) => section.name))];

          // 构建部门选项数组
          this.sectionOptions = uniqueNames.map((name) => ({
            label: name,
            value: name,
          }));
        })
        .catch((error) => {
          console.log(error);
        });
    },
    getData() {
      this.$axios
        .get("/user3", {
          params: {
            q: `${this.formInline.search}`,
            _page: this.page,
            _limit: this.count,
          },
          headers: {
            "X-Total-Count": "true",
          },
        })
        .then(({ data, headers }) => {
          this.total = Number(headers["x-total-count"]);
          this.tableData = data;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    search() {
      this.page = 1;
      const params = {
        q: this.formInline.search,
        _page: this.page,
        _limit: this.count,
      };

      if (this.selectedOption) {
        params.bumen = this.selectedOption;
      }
      if (this.selectedOptionA) {
        params.quanxian = this.selectedOptionA;
      }

      this.$axios
        .get("/user3", { params })
        .then(({ data, headers }) => {
          this.total = Number(headers["x-total-count"]);
          this.tableData = data;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    handleAdd() {
      this.isAddDialogVisible = true;
      this.newDepartment = {
        id: "",
        name: "",
        bumen: "",
        quanxian: "",
        time: "",
        ren: "",
        status: "",
      };
    },

    handleAddDialogClose() {
      this.isAddDialogVisible = false;
    },
    handleAddDepartment() {
      this.isAddDialogVisible = false;
      this.$axios
        .post("/user3", {
          id: this.newDepartment.id,
          name: this.newDepartment.name,
          bumen: this.newDepartment.bumen,
          quanxian: this.newDepartment.quanxian,
          time: this.newDepartment.time,
          ren: this.newDepartment.ren,
        })
        .then(({ data }) => {
          if (data) {
            this.$message({
              message: "添加成功",
              type: "success",
              duration: 1400,
            });
            this.newDepartment.id = "";
            this.newDepartment.name = "";
            this.newDepartment.bumen = "";
            this.newDepartment.quanxian = "";
            this.newDepartment.time = "";
            this.newDepartment.ren = "";
            this.getData();
          } else {
            alert("添加失败");
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    handleEdit(row) {
      this.isEditDialogVisible = true;
      this.editDepartment = { ...row };
    },
    handleSaveDepartment() {
      this.isEditDialogVisible = false;
      this.$axios
        .put(`/user3/${this.editDepartment.id}`, {
          name: this.editDepartment.name,
          bumen: this.editDepartment.bumen,
          quanxian: this.editDepartment.quanxian,
          time: this.editDepartment.time,
          ren: this.editDepartment.ren,
        })
        .then(({ data }) => {
          if (data) {
            this.$message({
              message: "更新成功",
              type: "success",
              duration: 1400,
            });
            this.getData();
          } else {
            alert("更新失败");
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    handleEditDialogClose() {
      this.isEditDialogVisible = false;
    },
    handleLook(row) {
      this.isViewDialogVisible = true;
      this.viewDepartment = { ...row };
    },
    handleViewDialogClose() {
      this.isViewDialogVisible = false;
    },
    handleDelete(row) {
      this.confirmDeleteDepartment = row;
      this.isConfirmDeleteVisible = true;
    },
    deleteDepartment(row) {
      const index = this.tableData.indexOf(row);
      if (index !== -1) {
        this.$axios
          .delete(`/user3/${row.id}`)
          .then(({ data }) => {
            if (data) {
              this.$message({
                message: "删除成功",
                type: "success",
                duration: 1400,
              });
              this.tableData.splice(index, 1);
              if (index === 0 && this.page > 1) {
                this.page--;
              }
              this.getData();
            } else {
              alert("删除失败");
            }
          })
          .catch((error) => {
            console.log(error);
          });
      }
      this.resetConfirmDelete();
    },
    resetConfirmDelete() {
      this.isConfirmDeleteVisible = false;
      this.confirmDeleteDepartment = null;
    },
  },
  mounted() {
    this.getSectionData(); // 调用getSectionData函数获取部门数据并处理部门选项
    this.getData(); // 调用getData函数获取表格数据
  },
};
</script>

<style lang="less" scoped>
.flex-container {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.block {
  margin-right: 370px;
  margin-top: -6px;
}

.data-count {
  margin-left: 380px;
}
.wen {
  margin-left: 160px;
}
.dialog-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: calc(100% - 52px);
}

#hezi {
  width: 100%;
  background-color: #fff;
  position: relative;
}

.header {
  width: calc(100%-20px);
  height: 60px;
  border: 1px solid #eee;
  line-height: 60px;
  padding-left: 20px;
  font-size: 20px;
}

.right {
  position: relative;
  width: 1200px;

  margin-top: -40px;
  overflow: hidden;
}

.buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  margin-top: 50px;
}

.el-input {
  width: 250px;
}

.tree-width {
  width: 250px;
}

.el-pagination {
  margin-top: 15px;
  margin-left: 350px;
}

.dialog-content .el-form-item {
  margin-bottom: 10px;
}

.dialog-content .el-form-item {
  width: 100%;
}
.dialog-content .el-form-item .el-input {
  width: 400px;
}
</style>
